package com.cardone.platform.authority.util;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import lombok.Getter;
import lombok.Setter;

import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.cardone.context.ContextHolder;
import com.cardone.platform.authority.dto.RoleDto;
import com.cardone.platform.authority.service.RoleService;
import com.cardone.platform.usercenter.dto.UserDto;
import com.cardone.platform.usercenter.util.UserUtils;

/**
 * 角色工具类
 *
 * @author yaohaitao
 *
 */
public class RoleUtils {
	/**
	 * 默认角色代码集合
	 */
	@Setter
	@Getter
	private static List<String> defaultRoleCodeList;

	/**
	 * 初化化超级标识
	 */
	private static boolean initSuperId;

	/**
	 * 超级标识
	 */
	private static String superId;

	/**
	 * 超级角色
	 */
	@Setter
	private static RoleDto superRole;

	/**
	 * 初始化超级管理员标识
	 */
	public static void initSuperId() {
		if (RoleUtils.initSuperId) {
			return;
		}

		if (RoleUtils.superRole == null) {
			return;
		}

		RoleUtils.superId = ContextHolder.getBean(RoleService.class).readIdByCode(RoleUtils.superRole);

		RoleUtils.initSuperId = true;
	}

	/**
	 * 是否超级管理员
	 *
	 * @return 是否超级管理员
	 */
	public static boolean isSuper() {
		final HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

		return RoleUtils.isSuper(request);
	}

	/**
	 * 是否超级管理员
	 *
	 * @param request
	 * @return 是否超级管理员
	 */
	public static boolean isSuper(final HttpServletRequest request) {
		final UserDto loginUser = UserUtils.findForLogin(request);

		return RoleUtils.isSuper(loginUser);
	}

	/**
	 * 是否超级管理员
	 *
	 * @param roleIdList
	 * @return 是否超级管理员
	 */
	public static boolean isSuper(final List<String> roleIdList) {
		if (CollectionUtils.isEmpty(roleIdList)) {
			return false;
		}

		RoleUtils.initSuperId();

		return CollectionUtils.contains(roleIdList.iterator(), RoleUtils.superId);
	}

	/**
	 * 是否超级管理员
	 *
	 * @param loginUser
	 *          用户对象
	 * @return 是否超级管理员
	 */
	public static boolean isSuper(final UserDto loginUser) {
		return RoleUtils.isSuper(loginUser.getRoleIdList());
	}
}
